import random
import json
import time

import requests
from handle_excel import HandleExcel

he = HandleExcel()  # 实例化HandleExcel类
list_token = he.get_columns_value('A')  # 从文件中提取token
# print(list_token)
# print(len(list_token))

roundId = 133160  # 定义直播间id
# 定义查题目的接口地址    gateway-beta
url_getSubjectDetailByRoundId = "https://gateway.fengjinketang.com/api/edu-fengjin-sale-web/subject/getSubjectDetailByRoundId"
# 定义提交选项的接口地址
url_submit = "https://gateway.fengjinketang.com/api/edu-fengjin-sale-web/subject/submit"

num = 1
for token in list_token:
    # print('token:' + token)
    # 获取当前时间的13位时间戳
    timestamp = int(round(time.time() * 1000))

    payload = "{\"appId\":\"wx101d5aebaa6b0c29\",\"timestamp\":%s,\"appVersionCode\":20240903,\"data\":{\"roundId\":%s}}" % (
        str(timestamp), str(roundId))
    headers = {
        'authorization': token,
        'istio-v': 'feature-hd-living',
        'ostype': 'h5',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'systemtype': 'iOS',
        'token': token,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json;charset=utf-8'
    }

    response = requests.request("POST", url_getSubjectDetailByRoundId, headers=headers, data=payload)

    subjectJson = json.loads(response.json()["data"]["subjectJson"])  # 从返回值中获取题目json
    publishCode = response.json()["data"]["publishCode"]  # 从返回值中获取唯一标识

    topic_option_list = [key for key in subjectJson["optionMap"].keys() if isinstance(key, str)]  # 取出题目中的所有选项key，组成列表

    random_element = random.choice(topic_option_list)  # 从列表中随机选取一个元素
    correct_answer = subjectJson["correctAnswer"]  # 从返回值中取出正确的答案
    # 定义是否答对，默认为否    并与随机数进行比较，一致则定义为是
    answerState = 0
    if random_element == correct_answer:
        answerState = 1
    # print(subjectJson)
    # print(type(json.dumps(subjectJson)))

    payload = {"appId": "wx101d5aebaa6b0c29", "timestamp": timestamp, "appVersionCode": 20240903,
               "data": {"publishCode": f"{publishCode}", "subjectJson": f"{json.dumps(subjectJson,ensure_ascii=False)}",
                        "roundId": f"{str(roundId)}",
                        "roundState": 1, "studentAnswer": f"{str(random_element)}", "answerState": answerState}}
    headers = {
        'authorization': token,
        'istio-v': 'feature-hd-living',
        'ostype': 'h5',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'systemtype': 'iOS',
        'token': token,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json;charset=utf-8'
    }

    response = requests.request("POST", url_submit, headers=headers, json=payload)
    # print(response.request.body)
    print(f'用户{num}提交成功-----{token}')
    num += 1
    # time.sleep(1111)
